#!/bin/bash
set -e

HOST_ARCH=${HOST_ARCH:-amd64}
ARCH=${ARCH:-amd64}

declare -A qemuarch=( ["amd64"]="x86_64" ["arm"]="arm" ["arm64"]="aarch64" )
declare -A ttycons=( ["amd64"]="ttyS0" ["arm"]="ttyAMA0" ["arm64"]="ttyAMA0" )
declare -A machine=( ["amd64"]="" ["arm"]="-M virt" ["arm64"]="-M virt" )
declare -A cpu=( ["amd64"]="" ["arm"]="-cpu cortex-a8" ["arm64"]="-cpu cortex-a57" )
declare -A network=(
    ["amd64"]="-net nic,vlan=0,model=virtio -net user,vlan=0,hostfwd=tcp::2222-:22,hostname=rancher-dev"
    ["arm"]="-netdev user,id=unet,hostfwd=tcp::2222-:22,hostname=rancher-dev -device virtio-net-device,netdev=unet"
)
network["arm64"]=${network["arm"]}

hd_amd64() {
    echo "-drive if=virtio,file=$1"
}
hd_arm() {
    echo "-drive if=none,id=hd0,file=$1 -device virtio-blk-device,drive=hd0"
}
declare -A hd=( ["amd64"]="hd_amd64" ["arm"]="hd_arm" ["arm64"]="hd_arm" )

cd_amd64() {
    echo "-hdc $1"
}
cd_arm() {
    echo "-drive if=none,id=cd0,file=$1 -device virtio-blk-device,drive=cd0"
}
declare -A cd=( ["amd64"]="cd_amd64" ["arm"]="cd_arm" ["arm64"]="cd_arm" )

BUILD=build
BASE=$(pwd)
UNAME=$(uname)

KERNEL=${BASE}/build/kernel/vmlinuz
INITRD_SRC=${BASE}/build/initrd
INITRD=${BASE}/build/initrd.tmp
#LINUXMOD=${BASE}/build/kernel/linuxmods


QEMU=1
FORMAT=1
RM_USR=1
REBUILD=1

QEMUARCH=${qemuarch["${ARCH}"]}
TTYCONS=${ttycons["${ARCH}"]}

if [ "$ENGINE_REGISTRY_MIRROR" != "" ]; then
    REGISTRY_MIRROR="rancher.bootstrap_docker.registry_mirror=${ENGINE_REGISTRY_MIRROR} rancher.system_docker.registry_mirror=${ENGINE_REGISTRY_MIRROR} rancher.docker.registry_mirror=${ENGINE_REGISTRY_MIRROR}"
fi

DEFAULT_KERNEL_ARGS="printk.devkmsg=on rancher.password=rancher console=tty1 rancher.autologin=tty1 console=${TTYCONS} rancher.autologin=${TTYCONS} ${REGISTRY_MIRROR} "
